<template>
  <div id="single-choice"
      class="task-single-choice">
      <!-- 每个单选 -->
      <div class="task-single-main"
        :id="'single'+opIndex"
        v-for="(option,opIndex) in FormData.singleData"
        :key="opIndex">
        <el-card shadow="never">
          <div slot="header" class="clearfix" style="margin: 0 0 0 0;">
              <div style="width:470px;float:left;"> {{opIndex+1}}.{{option.subject}}({{option.score}}分) </div>
              <div style="float: right; margin-top:-5px;">
                <el-button-group style="float: right;" >
                  <el-button icon="el-icon-edit" @click="isEditStatus(option)"></el-button>
                  <el-button icon="el-icon-delete" @click="deleteQuestion(FormData.singleData, option, opIndex)"></el-button>
                  <el-button icon="el-icon-arrow-up" @click="moveQuestion(FormData, opIndex, 'up')"></el-button>
                  <el-button icon="el-icon-arrow-down" @click="moveQuestion(FormData, opIndex, 'down')"></el-button>
                </el-button-group>
                <el-input style="width:35%;float: right;" v-if="option.isEdit" size="mid" placeholder="请输入分数" v-model.number="option.score" @input="scoreInput($event, option, opIndex)" @blur="checkRequired($event)">
                  <template slot="prepend">分数</template>
                </el-input>
              </div>
          </div>
          <!-- 整体 -->
        <div
          v-for="(choice,chIndex) in option.options"
          :key="chIndex">
          <el-radio
              class="task-el-radio task-el-single-option"
              style="margin-top:15px;"
              v-model="FormData.singleData[opIndex].answer" :label="option.options[chIndex]">
              {{ choiceList[chIndex] + ". "
              +choice}}
          </el-radio>
        </div>
          <el-collapse-transition>
            <div class="task-single-design design" v-show="option.isEdit">
              <div class="task-single-design-options-div" style="margin-top:25px;">
                <div class="task-single-design-options-box">
                  <div class="task-title-edit">题目编辑</div>
                    <el-input
                    type="textarea"
                    :autosize="{minRows:4}"
                    class="task-el-input "
                    style="width:100%;"
                    v-model="option.subject"
                    :placeholder="'请填写题目'"
                    @blur="checkTaskTitle($event)">
                  </el-input>
                  <el-row>
                    <el-col class="bg-purple grid-content" style="width:63.5%;"><span>选项文字</span></el-col>
                    <el-col class="bg-purple grid-content" style="margin-left:5px; width:11%;"><span>正确答案</span></el-col>
                    <el-col class="bg-purple grid-content" style="margin-left:5px; width:23%;"><span>操作栏</span></el-col>
                  </el-row>
                  <div class="task-single-design-options"
                    v-for="(choice,chIndex) in option.options"
                    :key="chIndex">
                      <div style="min-width:22px;">
                        {{choiceList[chIndex]}}：
                      </div>
                      <el-input
                        type="textarea"
                        :autosize="{minRows:1}"
                        class="task-el-input task-single-design-options-input"
                        v-model="option.options[chIndex]"
                        :placeholder="'请输入选项 '+choiceList[chIndex]+' 的内容'"
                        style="width:59%;"
                        @blur="checkChoiceList($event)">
                      </el-input>
                      <el-radio
                        class="task-el-radio task-el-single-option"
                        v-model="FormData.singleData[opIndex].answer"
                        :label="option.options[chIndex]"
                        style="margin-left:5%;width:5%;">
                      </el-radio>
                      <el-button-group style="margin-top:10px;margin-left:1.8vw;">
                        <el-button size="small" icon="el-icon-plus" @click="addOption(option,opIndex,chIndex)"></el-button>
                        <el-button size="small" icon="el-icon-delete" @click="deleteOption(option.options,chIndex,'option')"></el-button>
                        <el-button size="small" icon="el-icon-arrow-up" @click="moveOption(FormData.singleData[opIndex].options, chIndex, 'up')"></el-button>
                        <el-button size="small" icon="el-icon-arrow-down" @click="moveOption(FormData.singleData[opIndex].options, chIndex, 'down')"></el-button>
                      </el-button-group>
                  </div>
                  <div>
                    <el-button type="primary" style="margin-top:30px;" @click="createOrUpdateQuestion(opIndex)">完成编辑</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-transition>
        </el-card>
      <!-- 题目分割线 -->
      <div class="hr" v-if="opIndex!=FormData.singleData.length-1"/>
      </div>
      <div class="task-single-problom-editer">
      </div>
  </div>
</template>

<script>
import api from '../../../../../api'
export default {
  name: 'single-choice',
  props: ['FormData'],
  data () {
    return {
      s: 0,
      m: 0,
      j: 0,
      visible2: [],
      choiceList: ['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    }
  },
  mounted () {
    this.$emit('singleAnswer', 1)
    this.FormData.singleData.forEach(_ => {
      this.visible2.push(false)
    })
  },
  methods: {
    async scoreInput (e, option, opIndex) {
      var s = 0
      var m = 0
      var j = 0
      var p = 0
      await this.FormData.singleData.forEach(_ => {
        s += (_.score)
      })
      await this.FormData.multipleData.forEach(_ => {
        m += (_.score)
      })
      await this.FormData.judgeData.forEach(_ => {
        j += (_.score)
      })
      await this.FormData.programmingData.forEach(_ => {
        p += (_.score)
      })
      this.FormData.totalScore = await (s + m + j + p)
    },
    checkRequired (e) {
      if (!e.target.value) {
        this.$message({
          message: '请填写题目分数',
          type: 'warning'
        })
      } else {
        this.FormData.required = true
      }
    },
    checkChoiceList (e) {
      if (!e.target.value) {
        this.$message({
          message: '请填写选项',
          type: 'warning'
        })
        this.FormData.required = false
      } else {
        this.FormData.required = true
      }
    },
    checkTaskTitle (e) {
      if (!e.target.value) {
        this.$message({
          message: '请填写题干',
          type: 'warning'
        })
        this.FormData.required = false
      } else {
        this.FormData.required = true
      }
    },
    createOrUpdateQuestion (opIndex) {
      let data = this.FormData.singleData[opIndex]
      // 对单个问题的输入进行验证
      if (!this.FormData.required) {
        this.$message({
          message: '请填写完整题目的题目，选项，分数',
          type: 'error'
        })
      } else {
        // 发送数据到后端
        let passData = {
          homeworkId: this.FormData.homework_id,
          course_id: this.$route.params.courseId,
          description: data.subject,
          answers: [data.answer],
          choices: data.options,
          selectionProblemType: 'single',
          explanation: data.analysis,
          score: data.score
        }
        if (data.id) {
          // 修改单选题
          passData.id = data.id
          api['updateSelectionProblem'](passData).then(res => {
            this.updateHomeworkScore()
          }).catch((e) => {
          })
        } else {
          // 新增单选题
          api['createSelectionProblem'](passData).then(res => {
            this.FormData.singleData[opIndex].id = res.data.data.id
            this.updateHomeworkScore()
          }).catch((e) => {
          })
        }
        data.isEdit = false // 关闭题目编辑区
      }
    },
    updateHomeworkScore () {
      let passData = {
        section_id: this.FormData.sectionId,
        homeworkId: this.FormData.homework_id,
        title: this.FormData.title,
        selection_problems: this.FormData.selections,
        score: this.FormData.totalScore
      }
      api['updateHomework'](passData).then(res => {
      }).catch((e) => {
      })
    },
    moveOption (ArrayData, index, type) {
      const options = {
        up: () => {
          if (index === 0) {
            this.$message.warning('已经是第一个了，没法再向上移动了！')
            return
          }
          this.swapArray(ArrayData, index, index - 1)
        },
        down: () => {
          if (index + 1 === ArrayData.length) {
            this.$message.warning('已经是最后一题个，没法再向下移动了')
            return
          }
          this.swapArray(ArrayData, index, index + 1)
        }
      }
      options[type]()
    },
    isEditStatus (option) {
      option.isEdit = !option.isEdit
    },
    importQuestionBank (option, opIndex) {},
    scoreInputChange (e) {
    },
    singleBtnEvent (option, opIndex, type) {
      const options = {
        addToSingleData: () => {
          // 点击应该弹出模态框，让用户选择标签
          this.$message({
            message: '已将此题添加到单选题库',
            type: 'success'
          })
        }
      }
      options[type]()
    },
    deleteQuestion (ArrayData, option, opIndex) {
      api['deleteSelectionProblem'](this.FormData.homework_id, this.FormData.singleData[opIndex].id).then(res => {
        this.$message({
          message: '题目已被删除',
          type: 'success'
        })
        ArrayData.splice(opIndex, 1)
        this.visible2[opIndex] = false
        this.scoreInput()
      })
    },
    // 删除选项
    deleteOption (option, opIndex, type) {
      const options = {
        design: () => {
        },
        option: () => {
          if (option.length <= 2) {
            return this.$message({
              message: '单选题型最少两个选项',
              type: 'warning'
            })
          }
          option.splice(opIndex, 1)
        }
      }
      options[type]()
    },
    // 添加选项按钮
    addOption (option, opIndex, chIndex) {
      this.FormData.singleData[opIndex].options.splice(chIndex + 1, 0, '')
    },
    // 移动 点击的题 的位置
    // arr 点击的位置 移动的方式
    moveQuestion (ArrayData, index, type) {
      const options = {
        'down': () => {
          if (index + 1 === ArrayData.singleData.length) {
            this.$message.warning('已经是最后一题个，没法再向下移动了')
            return
          }
          this.swapArray(ArrayData.singleData, index, index + 1)
          setTimeout(() => {
            document.getElementById('single' + (index + 1)).scrollIntoView({ block: 'start', behavior: 'smooth' })
          }, 200)
        },
        'up': () => {
          if (index === 0) {
            this.$message.warning('已经是第一个了，没法再向上移动了！')
            return
          }
          this.swapArray(ArrayData.singleData, index, index - 1)
          setTimeout(() => {
            document.getElementById('single' + (index - 1)).scrollIntoView({ block: 'start', behavior: 'smooth' })
          }, 200)
        }
      }
      options[type]()
    },
    swapArray (arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
    }
  }
}
</script>

<style lang="less" scoped>
  .el-row {
    margin-top: 20px;
    margin-bottom: 20px;
    width: 100%;
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #E4E7ED;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    line-height: 36px;
    text-align:center;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .required {
    border: 1px solid red;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
</style>
